import datetime

from docx.shared import Cm
from docxtpl import DocxTemplate, InlineImage, Listing


class ReportGenerator:
    def __init__(
        self,
        docx_template_path,
        report_output_path,
        script_to_insert_path,
        temporary_images_path_plot_list,
    ):
        self.docx_template_path = docx_template_path
        self.temporary_image_path_plot_list = temporary_images_path_plot_list
        self.script_to_insert_path = script_to_insert_path
        self.report_output_path = report_output_path

    def generate_report(self):
        # Импортируем шаблон
        docx_template = DocxTemplate(self.docx_template_path)

        # Прочитаем код из скрипта для вставки в отчет
        with open(self.script_to_insert_path, "r") as f:
            the_listing_with_newlines = f.read()

        # Сопоставляем метки в документе docx с объектами Python
        students_list = [
            {"name": "Узбяков Р.Р.", "group": "АК1-111"},
            {"name": "Ольховой Я.С.", "group": "АК1-111"},
            {"name": "Кузнецов К.А.", "group": "АК2-112"},
        ]
        stud_string = ""
        for s in students_list:
            stud_string = stud_string + f"{s['name']}\t{s['group']}\n"

        context = {
            "title": "ДЗ расчет Баллистики ИСЗ в python",
            "students": stud_string,
            "t": "\t\t\t\t",
            "day": datetime.datetime.now().strftime("%d"),
            "month": datetime.datetime.now().strftime("%m"),
            "year": datetime.datetime.now().strftime("%Y"),
            "listing": Listing(the_listing_with_newlines),
        }

        # Импортируем картинки с сохраненными графиками в документ
        for temp_dict in self.temporary_image_path_plot_list:
            for key, value in temp_dict.items():
                context[f"{key}"] = InlineImage(docx_template, str(value), Cm(12))

        # Применяем контекст и сохраняем отчет
        docx_template.render(context)
        docx_template.save(self.report_output_path)
